package xyz.zhzby.cyzx.ucenter.service.impl;

import org.springframework.stereotype.Service;
import xyz.zhzby.cyzx.security.entity.User;
import xyz.zhzby.cyzx.security.util.CyzxSecurityContextHolder;
import xyz.zhzby.cyzx.servicebase.domain.RestResponse;
import xyz.zhzby.cyzx.servicebase.exception.BusinessException;
import xyz.zhzby.cyzx.servicebase.utils.StringUtils;
import xyz.zhzby.cyzx.ucenter.service.VerificationService;
import xyz.zhzby.cyzx.ucenter.util.MailUtils;
import xyz.zhzby.cyzx.ucenter.util.RedisUtil;
import xyz.zhzby.cyzx.ucenter.util.SmsUtils;

/**
 * @author zby
 * @date 2021/12/17
 */
@Service
public class VerificationServiceImpl implements VerificationService {

    @Override
    public RestResponse<String> sendMailCode(String email) {
        User subject = CyzxSecurityContextHolder.getSubject();
        //如果传参为空说明已经绑定邮箱，直接取就行
        if (StringUtils.isNullOrBlank(email)) {
            email = subject.getEmail();
        }
        String code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        try {
            MailUtils.sendVerificationCode(email, code);
            RedisUtil.setVerificationCode("code:email:" + subject.getUsername(), code);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("发送失败，请重试");
        }
        return RestResponse.success("发送成功，请注意查收");
    }

    @Override
    public RestResponse<String> verifyEmailCode(String code) {
        User subject = CyzxSecurityContextHolder.getSubject();
        String verificationCode = RedisUtil.getVerificationCode("code:email:" + subject.getUsername());
        if (code.equals(verificationCode)) {
            return RestResponse.success("身份验证成功");
        }
        return RestResponse.fail("验证码错误");
    }

    @Override
    public RestResponse<String> sendSmsCode(String phone) {
        User subject = CyzxSecurityContextHolder.getSubject();
        //如果传参为空说明已经绑定邮箱，直接取就行
        if (StringUtils.isNullOrBlank(phone)) {
            phone = subject.getPhone();
        }
        String code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        try {
            SmsUtils.sendVerificationCode(phone, code);
            RedisUtil.setVerificationCode("code:phone:" + subject.getUsername(), code);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("发送失败，请重试");
        }
        return RestResponse.success("发送成功，请注意查收");
    }

    @Override
    public RestResponse<String> verifySmsCode(String code) {
        User subject = CyzxSecurityContextHolder.getSubject();
        String verificationCode = RedisUtil.getVerificationCode("code:phone:" + subject.getUsername());
        if (code.equals(verificationCode)) {
            return RestResponse.success("身份验证成功");
        }
        return RestResponse.fail("验证码错误");
    }
}
